<template>
  <el-card>
    <div class="mb-20px">
      <h4>{{ id === -1 ? '新增' : '编辑' }}</h4>
    </div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      v-loading="formLoading"
    >
      <el-form-item label="资讯ID" prop="id">
        <el-input :modeValue="formData.id" disabled placeholder="创建后自动生成" />
      </el-form-item>
      <el-form-item label="资讯名称" prop="informationName">
        <el-input v-model="formData.informationName" placeholder="请输入资讯名称" />
      </el-form-item>
      <el-form-item label="显示顺序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入显示顺序" type="number" min="0" />
      </el-form-item>
      <el-form-item label="上传图片" prop="imagePath">
        <div class="flex items-end">
          <UploadImg v-model="formData.imagePath" />
          <span class="ml-20px">1080px*1920px</span>
        </div>
      </el-form-item>
      <el-form-item label="详情" prop="details">
        <Editor v-model="formData.details" height="500px" />
      </el-form-item>
      <el-form-item label="显示状态" prop="status">
        <el-switch v-model="formData.status" :active-value="0" :inactive-value="1" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-input
          :modelValue="formData.createTime && formatDate(formData.createTime)"
          disabled
          placeholder="创建后自动生成"
        />
      </el-form-item>
    </el-form>
    <div>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button
        @click="
          () => {
            $router.back()
            delVisitedView(route)
          }
        "
        >取 消</el-button
      >
    </div>
  </el-card>
</template>
<script setup lang="ts">
import { MarketInformationApi, MarketInformation } from '@/api/biz/marketinformation'
import { formatDate } from '@/utils/formatTime'
import { useTagsViewStore } from '@/store/modules/tagsView'

const { delVisitedView } = useTagsViewStore()
const route = useRoute()
const router = useRouter()

/** 市场资讯 表单 */
defineOptions({ name: 'MarketInformationForm' })
const id = +useRoute().params.id

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  informationName: undefined,
  sort: undefined,
  status: 0,
  recommendedStatus: 1,
  imagePath: undefined,
  details: undefined,
  createTime: undefined
})
const formRules = reactive({
  informationName: [{ required: true, message: '资讯名称不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '显示状态不能为空', trigger: 'blur' }],
  imagePath: [{ required: true, message: '图片不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MarketInformationApi.getMarketInformation(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MarketInformation
    if (formType.value === 'create') {
      await MarketInformationApi.createMarketInformation(data)
      message.success(t('common.createSuccess'))
    } else {
      await MarketInformationApi.updateMarketInformation(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    router.back()
    delVisitedView(route)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    informationName: undefined,
    sort: undefined,
    status: 0,
    recommendedStatus: 1,
    imagePath: undefined,
    details: undefined,
    createTime: undefined
  }
  formRef.value?.resetFields()
}

open(id === -1 ? 'create' : 'update', id === -1 ? undefined : id)
</script>
